// @ts-ignore
import { ready as udcReady } from './udc-sdk-esm';
import getSearchParams, { getFormateParam } from './getSearchParams';
import bpmLog from './log';
import { MESSAGE_TYPE } from './messageTypeEnum';
import { PERMISSION_ENUM } from './permissionEnum';
import BpmSdk from './sdk';

declare global {
  interface Window {
    __BPM_OPEN_SDK__: Record<string, any>;
  }
}
type ModelType = 'iframe' | 'normal';
type FunctionType = (...args: any[]) => any;
enum Scope {
  UDC = 'UDC',
  BPM = 'BPM',
}

interface IReady {
  version?: string;
  tenant?: string;
  mode: ModelType;
}
export type CallBackType = (instance: any, data: any) => Promise<any>;

interface IOpenSdk {
  closeWindow: () => void;
  registerAction: (
    actionName: string,
    callback?: FunctionType | undefined,
  ) => any;
  destroy: () => void;
  postMessage: (message: any) => void;
  onProcessStatus: (callback: FunctionType) => void;
  registerMoreAction: (
    actionNames: string[],
    callback?: FunctionType | undefined,
  ) => any;
  setFormData: (cb: any) => void;
  getFormData: () => any;
  emitAction: (message: any) => void;
  getActionInfo: (actionName: string, callback?: FunctionType | undefined) => Promise<void>;
}
const bpmInstance = new BpmSdk();

export const getSdk = (): IOpenSdk => {
  let sdk = window?.__BPM_OPEN_SDK__;
  if (!sdk) {
    sdk = bpmInstance?.getApi();
  }

  return sdk as IOpenSdk;
};

export const ready = (config: IReady, callback?: any) => {
  const bpmApi = bpmInstance.getApi();

  return new Promise((resolve) => {
    udcReady(config, (instance: any) => {
      const udcApi = instance?.getCustomApi();
      function getApi(scope: string) {
        if (scope === Scope.UDC) {
          return udcApi;
        }
        return bpmApi;
      }

      const destroy = () => {
        udcApi?.destroy?.();
        bpmApi?.destroy?.();
        bpmLog('注销事件啦');
      };
      const openApi = {
        ...bpmApi,
        destroy,
        getApi,
        insertBtnForToolbar: udcApi.insertBtnForToolbar,
      };

      if (!window?.__BPM_OPEN_SDK__?.insertBtnForToolbar) {
        window.__BPM_OPEN_SDK__ = openApi;
      }
      resolve(openApi);
      callback?.(openApi);
    });
  });
};

export { MESSAGE_TYPE, PERMISSION_ENUM, getFormateParam, getSearchParams };
export default ready;
